package com.leyou.user.web;

import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.local.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.dto.AddressDTO;
import com.leyou.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("info")
public class UserController {


    @Autowired
    private UserService userService;

    /**
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> checkDataExist(
            @PathVariable("data") String data, @PathVariable("type") Integer type) {

        return ResponseEntity.ok(userService.checkDataExist(data, type));
    }

    /**
     * @param phone
     * @return
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendMessage(@RequestParam("phone") String phone) {
        userService.sendMessage(phone);

        return ResponseEntity.noContent().build();
    }

    /**
     * @param user
     * @param code BindingResult 校验结果,防止
     * @return
     */
    @PostMapping
    public ResponseEntity<Void> register(User user, BindingResult result,
                                         @RequestParam("code") String code) {
        //校验结果
        if (result.hasErrors()) {
            //参数异常
            throw new LyException(400, "请求参数有误");
        }
        userService.register(user, code);
        return ResponseEntity.noContent().build();
    }

    @GetMapping
    public ResponseEntity<UserDTO> queryUserByPhoneAndPassword(
            @RequestParam("username") String username,
            @RequestParam("password") String password) {

        return ResponseEntity.ok(userService.queryUserByPhoneAndPassword(username, password));

    }

    @GetMapping("me")
    public ResponseEntity<UserDetails> whoAmI() {
        // 从上下文中获取用户，并返回
        return ResponseEntity.ok(UserContext.getUser());
    }


}